package com.moon.aspects;




import com.moon.annotations.DataSource;
import com.moon.utils.DataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Order(-1)// 保证该AOP在@Transactional之前执行
public class DynamicDataSourceAspect {

    @Pointcut("@annotation(com.moon.annotations.DataSource)")
    public void dataSourcePointcut() {}

    @Around("dataSourcePointcut()")
    public Object switchDataSource(ProceedingJoinPoint point) throws Throwable {
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        String dsName = dataSource.value();
        try {
            DataSourceContextHolder.setDataSourceKey(dsName);
            return point.proceed();
        } finally {
            DataSourceContextHolder.clear();
        }
    }
}
